import { _decorator, Component, Node, Button, instantiate, view, macro } from 'cc';
import { ResMgr } from './ResMgr';

export class UICtrl extends Component {
    protected view = {};

    load_all_object(root, path) {
        for (let i = 0; i < root.children.length; i++) {
            this.view[path + root.children[i].name] = root.children[i];
            if (root.children[i].children.length > 0) {
                this.load_all_object(root.children[i], path + root.children[i].name + "/");
            }
        }
    }

    protected onLoad(): void {
        this.view = {};
        this.load_all_object(this.node, "");
        //view.setOrientation(macro.ORIENTATION_LANDSCAPE);
    }

    public add_button_listener(view_name: string, caller, func: Function): void {
        let view_node = this.view[view_name];
        if (view_node == null) {
            console.error("can not find button named " + view_name);
            return;
        }
        let btn = view_node.getComponent(Button);
        if (btn == null) {
            console.error("can not find button named " + view_name);
            return;
        }
        view_node.on(Node.EventType.MOUSE_DOWN, func, caller);
    }
}


export default class UIMgr extends Component {
    private Canvas: Node = null;
    public static Instance: UIMgr = null;
    private uiMap = {};


    onLoad(): void {
        if (UIMgr.Instance == null) {
            UIMgr.Instance = this;
        }
        else {
            this.destroy();
            return;
        }
        this.Canvas = this.node;
    }

    public show_ui(ui_name: string, parent: Node = null, path?: string, hasCtrl: boolean = true): any {
        if (parent == null) {
            parent = this.Canvas;
        }
        let UIPath = "Prefabs/" + ui_name;
        if (path != null) {
            UIPath = "Prefabs/" + path + "/" + ui_name;
        }

        let prefab = ResMgr.Instance.getAsset("GUI", UIPath);
        let item = null;
        if (prefab != null) {
            item = instantiate(prefab);

            if (hasCtrl) {
                item.addComponent(ui_name + "_Ctrl");
            }
            if (parent != null) {
                parent.addChild(item);
                this.uiMap[ui_name] = item;
            }
        }

        return item;
    }

    public remove_ui(ui_name: string): void {
        let ui = this.uiMap[ui_name];
        if (ui != null) {
            ui.destroy();
            // ui.removeSelf();
            this.uiMap[ui_name] = null;
        }
    }

    public clearAll() {
        for (let key in this.uiMap) {
            let ui = this.uiMap[key];
            ui.destroy();
        }
        this.uiMap = {};
    }
}